//
//  CCScanQRcodeVC.m
//  Library
//
//  Created by hc-101 on 2019/11/6.
//  Copyright © 2019年 hc-101. All rights reserved.
//

#import "CCScanQRcodeVC.h"
#import <AVFoundation/AVFoundation.h>
#import "SelfHeader.h"
#import "UIImage+fixOrientation.h"
#import "MBProgressHUD+NMAHud.h"

static const CGFloat kHeightScale = 0.3;



API_AVAILABLE(ios(10.0))

@interface CCScanQRcodeVC ()<AVCaptureMetadataOutputObjectsDelegate,AVCapturePhotoCaptureDelegate>

@property (nonatomic, strong)AVCaptureSession *captureSession;

@property (nonatomic, strong)AVCaptureVideoPreviewLayer *reviewLayer;

@property (nonatomic, strong)AVCaptureMetadataOutput *metadateOutput;

@property (nonatomic,strong) AVCapturePhotoOutput *output11;// iOS 11以上
@property (nonatomic,strong) AVCaptureStillImageOutput *output4_10;// iOS 4~10

@property (nonatomic,strong)UIView *backgroudView;

//@property (nonatomic,strong)UIView *scanView;


@property (nonatomic,strong)UIButton *endScanBtn;


@property (nonatomic,strong)UIButton *takePhoneBtn;


@property (nonatomic,strong)UIButton *useBtn;
@property (nonatomic,strong)UIButton *reBtn;

@property (nonatomic, strong)UIImageView *animationImage;


@property (nonatomic, strong)NSMutableArray *dataArray;


@property (nonatomic, strong)UIView *contentView;


@property (nonatomic, strong)UIImageView *photoImageView;



///
@property (nonatomic, strong)UIView *contentBottomView;


@end

@implementation CCScanQRcodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
//    [self.view addSubview:self.scanView];

    
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        /// 用户是否允许摄像头使用
        NSString * mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        /// 不允许弹出提示框
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
            
            UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"摄像头访问受限" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertC animated:YES completion:nil];
            UIAlertAction * action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alertC addAction:action];
        }else{
            ////这里是摄像头可以使用的处理逻辑
            [self createrQrcode];
        }
    } else {
        /// 硬件问题提示
        
        NSLog(@"模拟器不可用");
    }
    
    
}

- (void)createrQrcode {
    //创建设备
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //判断设备是否自动聚焦
    if (captureDevice.autoFocusRangeRestrictionSupported) {
        //判断摄像头是否加锁成功
        if ([captureDevice lockForConfiguration:nil]) {
            captureDevice.autoFocusRangeRestriction = AVCaptureAutoFocusRangeRestrictionNear;
            [captureDevice unlockForConfiguration];
        }
    }
    
  
    
    //设置设备输入流
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:nil];
    
    //设置设备输出流
    _metadateOutput = [[AVCaptureMetadataOutput alloc]init];
    //设置代理回调输出值
    [_metadateOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
   

    
  

    //设置拍照质量
    if ([self.captureSession canSetSessionPreset:AVCaptureSessionPresetHigh]) {
        self.captureSession.sessionPreset = AVCaptureSessionPresetHigh;
    }
    
    if (@available(iOS 11.0,*)) {
        self.output11 = [[AVCapturePhotoOutput alloc] init];
        if ([self.captureSession canAddOutput:self.output11]) {
            [self.captureSession addOutput:self.output11];
        }
    }else{
        self.output4_10 = [[AVCaptureStillImageOutput alloc] init];
        self.output4_10.outputSettings = @{AVVideoCodecKey:AVVideoCodecJPEG};
        if ([self.captureSession canAddOutput:self.output4_10]) {
            [self.captureSession addOutput:self.output4_10];
        }
    }
    
    //设置扫码类型
    if ([self.captureSession canAddInput:deviceInput]) {
        [self.captureSession addInput:deviceInput];
    }
    if ([self.captureSession canAddOutput:_metadateOutput]) {
        [self.captureSession addOutput:_metadateOutput];
    }
 
    
//    //必须在添加之后才能设置扫描类型。
//    _metadateOutput.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeAztecCode];
    
    self.reviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.reviewLayer.frame = self.view.frame;
    [self.view.layer insertSublayer:self.reviewLayer atIndex:0];
    [self.view addSubview:self.backgroudView];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (![self.captureSession isRunning]) {
        [self.captureSession startRunning];
    }
    
//    [self starAnimation];
}



#pragma mark-----AVCaptureMetadataOutputObjectsDelegate

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    
    if (metadataObjects.count > 0 ) {
        
        AVMetadataMachineReadableCodeObject *obj = metadataObjects.firstObject;
        
//        [self.captureSession stopRunning];
//        self.animationImage.hidden = YES;
        [self theProcessingResults:obj.stringValue];
    }
}

- (AVCaptureSession *)captureSession{
    if (!_captureSession) {
        _captureSession = [[AVCaptureSession alloc]init];
    }
    return _captureSession;
}

- (AVCaptureVideoPreviewLayer *)reviewLayer {
    if (!_reviewLayer) {
        _reviewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
    }
    return _reviewLayer;
}



#pragma mark - get set

- (UIView *)backgroudView {
    if (!_backgroudView) {
        _backgroudView = [[UIView alloc]init];
        _backgroudView.frame = CGRectMake(0, Height_NavBar, SCREEN_WIDTH, SCREEN_HEIGHT - Height_NavBar - Height_bottomSafe);
        
        //全屏view
        
        self.contentBottomView.frame  = CGRectMake(0, SCREEN_HEIGHT-125-Height_bottomSafe-Height_NavBar, SCREEN_WIDTH, 125);
        
        
        [_backgroudView addSubview:self.contentBottomView];
        

        [self.contentBottomView addSubview:self.takePhoneBtn];
        
       
        self.takePhoneBtn.frame  = CGRectMake(SCREEN_WIDTH* 0.5 - 30, 0, 60, 60);
        
        self.takePhoneBtn.centerY   =  62.5;
        
        [_backgroudView addSubview:self.useBtn];
        self.useBtn.hidden  = YES;
        self.useBtn.frame  = CGRectMake(SCREEN_WIDTH-70-15, _backgroudView.height - 36-15, 70, 36);
        
        
        [_backgroudView addSubview:self.reBtn];
        self.reBtn.hidden  = YES;
        self.reBtn.frame  = CGRectMake(15, _backgroudView.height - 36-15, 70, 36);
      
        

        
//        self.labelView2.hidden  = NO;
//        CGSize  size  =  [self.labelView2.text sizeWithAttributes:@{NSFontAttributeName:self.labelView2.font}];
//        self.labelView2.frame  = CGRectMake(0, 40, size.width + 10, 30);
//        self.labelView2.centerX  = SCREEN_WIDTH * 0.5;
        
        
//        self.bottom = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT*kHeightScale, SCREEN_WIDTH, SCREEN_HEIGHT*(1-kHeightScale) - Height_NavBar)];
//        self.bottom.backgroundColor = [UIColor whiteColor];
//        [_backgroudView addSubview:self.bottom];//Qrbackgroud

//
//        self.animationImage  = [[UIImageView alloc]initWithImage:[UIImage imageNamed:MYBUNDLE_ForImageName(@"line")]];
//        self.animationImage.frame = CGRectMake(0, 0, SCREEN_WIDTH *0.6, 2);
//        self.animationImage.centerX  = SCREEN_WIDTH * 0.5;
//        self.animationImage.hidden = YES;
//        [_backgroudView addSubview:self.animationImage];
        
    

        
    }
    return _backgroudView;
}

-(UIView *)contentView{
    if(_contentView==nil){
        _contentView  = [[UIView alloc] init];
        _contentView.frame  = self.view.bounds;
    }
    
    return _contentView;
}


-(UIView *)contentBottomView{
    if(_contentBottomView==nil){
        _contentBottomView  = [[UIView alloc] init];
        _contentBottomView.backgroundColor  = [UIColor colorWithHexString:@"#000000" alpha:0.5];
    }
    return _contentBottomView;
}

-(UIImageView *)photoImageView{
    if(_photoImageView==nil){
        _photoImageView  =[[UIImageView alloc] init];
        _photoImageView.frame  = self.view.bounds;
    }
    return _photoImageView;
}





- (NSMutableArray *)dataArray{
    if(_dataArray == nil){
        _dataArray  = [NSMutableArray array];
//        _dataArray  = [ @[@"2343252452453",@"4526534537647",@"4526534537647",@"4526534537647"] mutableCopy ];
    }
    return _dataArray;
}

- (void)starAnimation {
    self.animationImage.hidden = NO;
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationRepeatCount:MAXFLOAT];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDuration:1.5];
    self.animationImage.frame = CGRectMake(SCREEN_WIDTH * 0.2, SCREEN_HEIGHT * kHeightScale, SCREEN_WIDTH * 0.6, 2);
    [UIView commitAnimations];
    
}

- (void)starAnimationFull{
    self.animationImage.hidden = NO;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationRepeatCount:MAXFLOAT];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDuration:1.5];
    self.animationImage.frame = CGRectMake(SCREEN_WIDTH * 0.2, _backgroudView.height * 0.7, SCREEN_WIDTH * 0.6, 2);
    [UIView commitAnimations];
}








-(UIButton *)takePhoneBtn{
    if(_takePhoneBtn ==nil){
        UIButton  *btn  =  [UIButton new];
        btn.backgroundColor  = [UIColor colorWithHexString:@"#f0f0f0"];
        [btn setRoundedRadius:30];
//        [btn setImage:[UIImage imageNamed:MYBUNDLE_ForImageName(@"takePhoto")] forState:UIControlStateNormal];
        [btn setTitle:@"拍摄" forState:UIControlStateNormal];
        btn.titleLabel.font  = [UIFont systemFontOfSize:16];
        [btn setTitleColor:[UIColor colorWithHexString:@"#1a1a1a"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(takePhoto:) forControlEvents:UIControlEventTouchUpInside];
        _takePhoneBtn  = btn;
    }
    return _takePhoneBtn;
}

-(UIButton *)useBtn{
    if(_useBtn ==nil){
        UIButton  *btn  =  [UIButton new];
        btn.backgroundColor  = [UIColor colorWithHexString:@"#0295eb"];
        [btn setTitle:@"使用" forState:UIControlStateNormal];
        btn.titleLabel.font  = [UIFont systemFontOfSize:16];
        [btn setRoundedRadius:4];
          [btn addTarget:self action:@selector(onUse:) forControlEvents:UIControlEventTouchUpInside];
        _useBtn  = btn;
    }
    return _useBtn;
}

-(UIButton *)reBtn{
    if(_reBtn ==nil){
        UIButton  *btn  =  [UIButton new];
        btn.backgroundColor  = [UIColor colorWithHexString:@"#ebebeb"];
        [btn setTitle:@"重拍" forState:UIControlStateNormal];
 
        [btn setTitleColor:[UIColor colorWithHexString:@"#1a1a1a"] forState:UIControlStateNormal];
        btn.titleLabel.font  = [UIFont systemFontOfSize:16];
        [btn setRoundedRadius:4];
          [btn addTarget:self action:@selector(reUse:) forControlEvents:UIControlEventTouchUpInside];
        _reBtn  = btn;
    }
    return _reBtn;
}



#pragma mark - click

- (void)onEndScanClick:(UIButton *)sender{
    
    sender.selected  = !sender.selected;
    self.animationImage.hidden = sender.selected;
    if(sender.isSelected){
         [self.endScanBtn setTitle:[NSString stringWithFormat:@"开始扫描共(%lu)条",(unsigned long)self.dataArray.count] forState:UIControlStateNormal];
        [self.captureSession  stopRunning];
       
        
    }else{
         [self.endScanBtn setTitle:[NSString stringWithFormat:@"结束扫描共(%lu)条",(unsigned long)self.dataArray.count] forState:UIControlStateNormal];
        [self.captureSession  startRunning];
    }
    
}






- (void)onTorchClick:(UIButton *)sender{
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch] && [device hasFlash]){
        [device lockForConfiguration:nil];
        if (!sender.selected) {
            [device setTorchMode:AVCaptureTorchModeOn];
            [device setFlashMode:AVCaptureFlashModeOn];
        } else {
            [device setTorchMode:AVCaptureTorchModeOff];
            [device setFlashMode:AVCaptureFlashModeOff];
        }
        [device unlockForConfiguration];
    }
    
    
    sender.selected = !sender.selected;
    

}




- (void)theProcessingResults:(NSString *)result {
    
//    if (![self.dataArray containsObject:result]){
//        [self.dataArray addObject:result];
//
//        [self.endScanBtn setTitle:[NSString stringWithFormat:@"结束扫描共(%lu)条",(unsigned long)self.dataArray.count] forState:UIControlStateNormal];
//        if(self.switchView.isOn && self.rightBtn.selected){  //自动拍照 且是全屏
//             [self takePhoto:nil];
//            NSString *res  = [NSString stringWithFormat:@"当前结果:%@ 已自动拍照",result];
//            [MBProgressHUD showToastWithText:res];
//
//        }else if(self.switchView.isOn==NO && self.rightBtn.selected){  //手动拍照
//            self.labelView2.hidden  = NO;
//            CGSize  size  =  [result sizeWithAttributes:@{NSFontAttributeName:self.labelView2.font}];
//            self.labelView2.text  = result;
//            self.labelView2.frame  = CGRectMake(0, 40, size.width + 10, 30);
//            self.labelView2.centerX  = SCREEN_WIDTH * 0.5;
//
//        }
//
//    }else{
//         if(!self.switchView.isOn  && self.rightBtn.selected){  //手动重复数据
//             self.labelView2.hidden  = NO;
//             CGSize  size  =  [result sizeWithAttributes:@{NSFontAttributeName:self.labelView2.font}];
//             self.labelView2.text  = result;
//             self.labelView2.frame  = CGRectMake(0, 40, size.width + 10, 30);
//             self.labelView2.centerX  = SCREEN_WIDTH * 0.5;
//         }
//    }
//
//    NSLog(@"%@",result);
    
}


#pragma mark - 拍照图片处理

-(void)onUse:(UIButton*)sender{
    UIImage  *image  = self.photoImageView.image;
    NSData *data  = UIImageJPEGRepresentation(image, 0.8);
    NSString  *str  = [self  createFile:data suffix:@".jpg"];
    
    [self handleSavedPath:str];
   
}

-(void)reUse:(UIButton*)sender{
    [self.contentView removeFromSuperview];
    
    [self.captureSession  startRunning];
    self.contentBottomView.hidden  = false;
    self.useBtn.hidden  = YES;
    self.reBtn.hidden  = YES;
    
}

- (void)takePhoto:(UIButton *)sender{
    if(sender== self.takePhoneBtn){
//        NSString *res  = [NSString stringWithFormat:@"当前结果:%@ 已手动拍照",self.labelView2.text];
//        [MBProgressHUD showToastWithText:res];
    }
    // 需要权限 “Privacy - Camera Usage Description”
    if (@available(iOS 11.0,*)) {
        AVCapturePhotoSettings *setting = [AVCapturePhotoSettings photoSettingsWithFormat:@{AVVideoCodecKey:AVVideoCodecTypeJPEG}];
        if (!setting) {
            NSLog(@"拍照失败");
            return ;
        }
        // 获取当前屏幕输出 ，实现代理
        [self.output11 capturePhotoWithSettings:setting delegate:self];
    }else{
        AVCaptureConnection *connect = [self.output4_10 connectionWithMediaType:AVMediaTypeVideo];
        if (!connect) {
            NSLog(@"拍照失败");
            return ;
        }
        [self.output4_10 captureStillImageAsynchronouslyFromConnection:connect completionHandler:^(CMSampleBufferRef _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
            if (imageDataSampleBuffer == NULL) {
                return ;
            }
            
            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *image = [UIImage imageWithData:imageData];
            NSLog(@"获取图片成功4~10 --- %@",image);
//            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
            
//            [self addWaterMark:image];
            [self addWaterMark:image name:self.name address:self.address time:self.time];
            
            [self setTackedPHoto];
        }];
        
    }
}

-(void)setTackedPHoto{
    self.useBtn.hidden  = NO;
    self.contentBottomView.hidden  = YES;
    self.reBtn.hidden  = NO;
}

#pragma mark - 拍摄静态照片
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
    if (error) {
        NSLog(@"拍摄照片异常---%@",error);
    }else{
        if (photo) {
            [self.captureSession  stopRunning];
            
            if (@available(iOS 11.0, *)) {
                CGImageRef cgImage = [photo CGImageRepresentation];
                UIImage * image = [UIImage imageWithCGImage:cgImage];
                image = [image rotation:UIImageOrientationRight];
                            
//                            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
                            NSLog(@"保存获取图片成功11111 --- %@",image);
                
//                [self addWaterMark:image];
                 [self addWaterMark:image name:self.name address:self.address time:self.time];
                 [self setTackedPHoto];
                
                
            }
            
            
        }
    }
    
}

-(void)addWaterMark:(UIImage*)image name:(NSString*)name address:(NSString*)address time:(NSString*)time  {
    
    [self.contentView  removeFromSuperview];
    
 
    
    // 计算图片的size
    CGSize imageSize = CGSizeMake(image.size.width, image.size.height);
    
    double scale  = imageSize.width  / [UIScreen mainScreen].bounds.size.width;
    
    // 开启图片类型的图形上下文
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    // 绘制图片
    [image drawAtPoint:CGPointZero];
//    // 水印的文字
//    NSString *str = @"水印文字";
//    // 绘制文字水印
//    [str drawAtPoint:CGPointMake(scale*10, 500) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15*scale], NSForegroundColorAttributeName:[UIColor redColor]}];
    
    // 水印的图片
    UIImage *logoImage = [UIImage createImageWithColor:[UIColor colorWithHexString:@"#000000" alpha:0.4] size:CGSizeMake((SCREEN_WIDTH-20)*scale, 122*scale)];
    // 绘制图片水印
    [logoImage drawAtPoint:CGPointMake(10*scale, (_backgroudView.height-122-30)*scale)];
    
 
        // 绘制文字水印
    [self.time drawAtPoint:CGPointMake(scale*20, (_backgroudView.height-122-30 + 14)*scale) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15*scale], NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    // 水印的图片
    UIImage *logoName = [UIImage imageNamed:MYBUNDLE_ForImageName(@"name")];
    
    logoName   = [UIImage scaleToSize:logoName size:CGSizeMake(logoName.size.width*scale, logoName.size.height*scale)];
    // 绘制图片水印
    [logoName drawAtPoint:CGPointMake(20*scale, (_backgroudView.height-122-30 + 44)*scale)];
    
    // 水印的图片
    UIImage *logoLocation = [UIImage imageNamed:MYBUNDLE_ForImageName(@"location")];
    
    logoLocation   = [UIImage scaleToSize:logoLocation size:CGSizeMake(logoLocation.size.width*scale, logoLocation.size.height*scale)];
    // 绘制图片水印
    [logoLocation drawAtPoint:CGPointMake(20*scale, (_backgroudView.height-122-30 + 71)*scale)];
    
    
    
    [self.name drawAtPoint:CGPointMake(scale*45, (_backgroudView.height-122-30 + 44)*scale) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15*scale], NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    if(self.address.length>20) {
        NSString  *str1 = [self.address substringToIndex:20];
        [str1 drawAtPoint:CGPointMake(scale*41, (_backgroudView.height-122-30 + 71)*scale) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15*scale], NSForegroundColorAttributeName:[UIColor whiteColor]}];
        
        NSString  *str2 = [self.address substringFromIndex:20];
        [str2 drawAtPoint:CGPointMake(scale*41, (_backgroudView.height-122-30 + 90)*scale) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15*scale], NSForegroundColorAttributeName:[UIColor whiteColor]}];
 
        
    }else{
        [self.address drawAtPoint:CGPointMake(scale*41, (_backgroudView.height-122-30 + 71)*scale) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15*scale], NSForegroundColorAttributeName:[UIColor whiteColor]}];
    }
    
    
    
   
    
    
    // 取图片
    image = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭图片类型的图形上下文
    UIGraphicsEndImageContext();
    
    
//    UIImage  *temp  = [UIImage imagew]
    
      self.photoImageView.image  = image;
    
    [self.contentView  addSubview:self.photoImageView];
    
//    UILabel  *label  = [[UILabel alloc] init];
//    label.frame   = CGRectMake(40, 200, 200, 44);
//
//    label.textColor  = [UIColor redColor];
//    label.text  = @"小明";
//
//    [self.contentView  addSubview:label];
    
    [self.view insertSubview:self.contentView belowSubview:self.topView];
    
    //点击使用

     
 }


- (NSString *)temporaryFilePath:(NSString *)suffix {
  NSString *fileExtension = [@"photo_watermark_%@" stringByAppendingString:suffix];
  NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString];
  NSString *tmpFile = [NSString stringWithFormat:fileExtension, guid];
  NSString *tmpDirectory = NSTemporaryDirectory();
  NSString *tmpPath = [tmpDirectory stringByAppendingPathComponent:tmpFile];
  return tmpPath;
}

- (NSString *)createFile:(NSData *)data suffix:(NSString *)suffix {
  NSString *tmpPath = [self temporaryFilePath:suffix];
  if ([[NSFileManager defaultManager] createFileAtPath:tmpPath contents:data attributes:nil]) {
    return tmpPath;
  } else {
    nil;
  }
  return tmpPath;
}


- (void)handleSavedPath:(NSString *)path {
  if (path) {
    self.result(path);
      [self dismissViewControllerAnimated:NO completion:nil];
  }
}











@end
